#include "tty.h"
#include "kernel.h"
#include "mm.h"
#include "idt.h"
#include "gdt.h"
#include "8259a.h"
#include "io.h"
#include "time.h"
#include "task.h"
#include "apic.h"
#include "asm.h"
#include "cpu.h"

long startup_time;

extern idtr_data_t idtr_data;
extern gdtr_data_t gdtr_data;

void ap_run_flow(void)
{
    *(uint8_t*) 0x7f33 = 0;
    asm volatile("lidt idtr_data");
    asm volatile("lgdt gdtr_data");

    kpcr_t* kpcr = kpcr_create(*(uint8_t*)0x7f2c);
    __asm__ __volatile__(
        "mov $0xc0000102, %%ecx;"
        "shr $32, %%rdx;"
        "wrmsr;"::"a"(kpcr), "d"(kpcr)
    );

    // 搞不明白为啥这里就不是%%rsp，寄存器不是应该2个%吗？
    __asm__ __volatile__(
        "swapgs;"
        "mov %gs:16, %rsp;"
        "swapgs;"
    );

    enable_local_apic();

    STI

    while (true)
    {
        printk("ap_run_flow\n");
        HLT
    }
    
}

void kernel64_main(void)
{
    init_8259a();
    console_init();
    phy_memory_init();
    idt_init();
    gdt_init();
    time_init();
    acpi_init();
    bsp_init();
    ap_init();

    task_init();

    console_init();
    cpu_broadcast();
    // cpu_signal(1);
        
    STI

    while(1) {
        printk("endless loop in kernel64_main()\n");
        HLT
    }
}